import { defineStore } from 'pinia'
import { ref } from 'vue'
import {
  loginAPI,
  getUserInfoAPI,
  getUserMenuAPI,
  getUserListAPI,
  deleteUserListItemAPI,
  addUserItemAPI,
  updateUserInfoAPI
} from '@/http/user'
import { MyStorage } from '@/utils/utils'
import { TOKEN } from '@/global/globalVariables'
import type {
  LoginResType,
  UserInfoDetailResType,
  UserInfoDetailType,
  UserListResType,
  UserListResOfDataArr
} from '@/interface/user/userType'

export const useUserStore = defineStore('user', () => {
  // 部分用户信息
  const userInfo = ref({
    id: '',
    username: '',
    token: MyStorage.get(TOKEN) ?? ''
  })
  // 详细用户信息
  const userInfoDetail = ref<UserInfoDetailType>()

  // 保存异步获取的路由表信息
  const routesAsync: any = ref([])

  // 存放用户列表数据
  const userList = ref<UserListResOfDataArr>()
  // 总的用户列表数量，不依赖查询条件
  const userListTotal = ref(0)

  // 用户请求接口全部放在pinia中
  const loginAction = async ({ username, md5pasw }: { username: string; md5pasw: string }) => {
    try {
      let res: LoginResType = await loginAPI({ username, md5pasw })
      if (+res.code === 200) {
        // 保存pinia
        userInfo.value = {
          id: res.id,
          username: res.username,
          token: res.token
        }
        // 保存本地存储
        MyStorage.set(TOKEN, res.token)
      }
      return {
        code: res.code,
        message: res.message
      }
    } catch (error) {}
  }
  //  获取详细用户信息
  const getUserInfoDetailAction = async () => {
    try {
      // 通过token获取用户数据
      let res: UserInfoDetailResType = await getUserInfoAPI()
      userInfoDetail.value = res.data
    } catch (error) {
      console.log('用户详情信息获取失败')
    }
  }

  const getRoutes = async () => {
    // 格式化路由表的函数
    const parseRoute = (data: any) => {
      let _newArray: any = [] //存放格式化的路由表
      data.forEach((item: any) => {
        let _path = item.path
        let _component = item.component
        let _name = item.name
        let _id = item.id

        let _icon = item.icon
        let children
        // 存在子路由需要进行处理
        if (item.children) {
          children = []
          item.children.forEach((child: any) => {
            if (child.redirect) {
              // 代表是跳转路由，该信息不需要进行处理
              children.push(child)
              return
            }

            // 二级路由
            let _path_ = child.path
            let _component_ = child.component
            let _name_ = child.name
            let _id_ = child.id
            let _route_ = {
              path: _path_,
              // component: (resolve) => {
              // 下面提示可以参考
              // The above dynamic import cannot be analyzed by Vite.
              // See https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations for supportes for supported dynamic import formats. If this is intended to be left as-is, you can useignore */ comm the /* @vite-ignore */ comment inside the import() call to suppress this warning.
              // Plugin: vite:import-analysis
              //   // require只能在webpack下使用
              //   // return require([`@/views/main/${_path}/${_component_}`], resolve)
              // }
              component: () => import(`../views/main/${_path}/${_component_}`),
              meta: {
                menuItemName: _name_,
                id: _id_
              }
            }
            children.push(_route_)
          })
        }

        let _route = {
          path: _path,
          // component: (resolve) => {
          //   // return require([`@/views/main/${_path}/${_component}`], resolve)
          // },
          component: () => import(`../views/main/${_path}/${_component}`),
          children,
          meta: {
            menuItemName: _name,
            id: _id,
            icon: _icon
          }
        }
        _newArray.push(_route)
      })
      return _newArray
    }
    let _newArray
    try {
      // 先获取用户信息后再获取用户所对应的权限列表的，所以这个时候用户详情信息中一定有数据
      let res = await getUserMenuAPI(userInfoDetail.value!._id, userInfoDetail.value!.role)
      _newArray = parseRoute(res.data)
      routesAsync.value = _newArray
    } catch (error) {
      console.log('获取权限路由失败')
    }
    return _newArray
  }

  // 获取用户列表数据
  const getUserList = async (data: any) => {
    try {
      let res: UserListResType = await getUserListAPI(data)
      userList.value = res.data
      userListTotal.value = res.totalCount
      return {
        code: res.code,
        message: res.message
      }
    } catch (error) {
      console.log('获取用户列表失败')
    }
  }

  // 删除用户数据
  const deleteUserListItem = async (id: number) => {
    try {
      let res: any = await deleteUserListItemAPI(id)
      if (res.code === 200) {
        ElMessage({
          message: '删除成功',
          type: 'success'
        })
        // 设计有点问题，应该将页码之类的默认参数放在pinia中
        await getUserList({ page: 1, pageSize: 5 }) //重新获取最新列表数据
      } else {
        ElMessage({
          message: '删除失败',
          type: 'error'
        })
      }
    } catch (error) {
      console.log('删除用户失败')
    }
  }

  // 添加用户
  const addUserItem = async (data: any) => {
    try {
      let res: any = await addUserItemAPI(data)
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: res.message
        })
        // 这里尽量再次进行校验判断返回结果
        await getUserList({ page: 1, pageSize: 5 }) //重新获取最新列表数据
      } else {
        ElMessage({
          type: 'error',
          message: res.message
        })
      }
    } catch (error) {
      console.log('添加用户失败')
    }
  }

  // 编辑某个用户数据
  const updateUserInfo = async (id: string, data: any) => {
    try {
      let res = await updateUserInfoAPI(id, { ...data, updatetime: Date.now() })
      if (res.code === 200) {
        ElMessage({
          type: 'success',
          message: '更新成功！'
        })
        // 重新获取列表数据
        await getUserList({ page: 1, pageSize: 5 })
      } else {
        ElMessage({
          type: 'warning',
          message: '更新失败'
        })
      }
    } catch (error) {
      console.log('更新用户数据失败')
    }
  }

  // 退出登录清空数据
  const clearUserStore = () => {
    Object.assign(userInfo.value, { id: '', username: '', token: '' })
    /* 这里不能将用户详情信息设置为空对象，否则一个用户退出的时候，不刷新的情况下再次换用户登录会出现问题
    因为在前置路由守卫中token内部会首先判断该变量是否为假，即没有数据，但是空对象不为假
    */
    // @ts-ignore
    userInfoDetail.value = null
    routesAsync.value = []
    userList.value = []
    userListTotal.value = 0
  }

  return {
    userInfo,
    userInfoDetail,
    routesAsync,
    userList,
    userListTotal,
    loginAction,
    getUserInfoDetailAction,
    getRoutes,
    clearUserStore,
    getUserList,
    deleteUserListItem,
    addUserItem,
    updateUserInfo
  }
})
